//
//  FMGVideoPlayView.m
//  网络视频播放(AVPlayer)
//
//  Created by apple on 15/8/16.
//  Copyright (c) 2015年 FMG. All rights reserved.
//

#import "FMGVideoPlayView.h"
#import "FullViewController.h"
#import <KSYMediaPlayer/KSYMediaPlayer.h>
#import <CommonCrypto/CommonDigest.h>
#import "AppDelegate.h"

@interface FMGVideoPlayView() <MyPlayRestoreDelegate>

// 播放器的Layer
@property (nonatomic, strong) KSYMoviePlayerController *player;

/* playItem */
@property (nonatomic, weak) AVPlayerItem *currentItem;

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIView *toolView;
@property (weak, nonatomic) IBOutlet UIButton *playOrPauseBtn;
@property (weak, nonatomic) IBOutlet UIButton *fullBtn;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;



// 记录当前是否显示了工具栏
@property (assign, nonatomic) BOOL isShowToolView;

@property (assign, nonatomic) BOOL finishedPlay;

/* 定时器 */
@property (nonatomic, strong) NSTimer *progressTimer;

/* 工具栏的显示和隐藏 */
@property (nonatomic, strong) NSTimer *showTimer;

/* 工具栏展示的时间 */
@property (assign, nonatomic) NSTimeInterval showTime;

/* 全屏控制器 */
@property (nonatomic, strong) FullViewController *fullVc;

#pragma mark - 监听事件的处理
- (IBAction)playOrPause:(UIButton *)sender;
- (IBAction)switchOrientation:(UIButton *)sender;
- (IBAction)slider;
- (IBAction)startSlider;
- (IBAction)sliderValueChange;

- (IBAction)tapAction:(UITapGestureRecognizer *)sender;
- (IBAction)swipeAction:(UISwipeGestureRecognizer *)sender;
- (IBAction)swipeRight:(UISwipeGestureRecognizer *)sender;
@property (weak, nonatomic) IBOutlet UIImageView *forwardImageView;

@property (weak, nonatomic) IBOutlet UIImageView *backImageView;

@end

@implementation FMGVideoPlayView


// 快速创建View的方法
+ (instancetype)videoPlayView
{
    return [[[NSBundle mainBundle] loadNibNamed:@"FMGVideoPlayView" owner:nil options:nil] firstObject];
}


- (void)awakeFromNib
{
    [super awakeFromNib];
}


- (void)initPlaying:(NSString *)mediaURL {
        [self initKSYAuth];
        self.currentMediaURL = mediaURL;
        NSString *urlStr =[NSString stringWithFormat:@"%@", mediaURL];
        NSURL *url = [NSURL URLWithString:urlStr];
        self.player = [[KSYMoviePlayerController alloc] initWithContentURL:url];
        self.player.scalingMode = MPMovieScalingModeFill;//缩放效果
        [self.player setControlStyle:MPMovieControlStyleFullscreen];
    
        [self.imageView.layer addSublayer:self.player.view.layer];
    
    // 设置工具栏的状态
    self.toolView.alpha = 0;
    self.isShowToolView = NO;
    
    self.forwardImageView.alpha = 0;
    self.backImageView.alpha = 0;
    
    // 设置进度条的内容
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"thumbImage"] forState:UIControlStateNormal];
    [self.progressSlider setMaximumTrackImage:[UIImage imageNamed:@"MaximumTrackImage"] forState:UIControlStateNormal];
    [self.progressSlider setMinimumTrackImage:[UIImage imageNamed:@"MinimumTrackImage"] forState:UIControlStateNormal];
    
    // 设置按钮的状态
    self.playOrPauseBtn.selected = NO;
    
    [self showToolView:YES];
    
}

- (void)fullPlaying {
   
}

- (void)restorePlaying {
    
}


- (void)initKSYAuth {
    NSString *time = [NSString stringWithFormat:@"%d",(int)[[NSDate date]timeIntervalSince1970]];
    NSString *sk = [NSString stringWithFormat:@"sff25dc4a428479ff1e20ebf225d113%@", time];
    NSString *sksign = [self MD5:sk];
    //[[KSYPlayerAuth sharedInstance]setAuthInfo:@"QYA0EEF0FDDD38C79913" accessKey:@"abc73bb5ab2328517415f8f52cd5ad37" secretKeySign:sksign timeSeconds:time];
}

- (NSString *)MD5:(NSString*)raw {
    const char *pointer = [raw UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);
    
    NSMutableString *string = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [string appendFormat:@"%02x",md5Buffer[i]];
    
    return string;
}

-(void)preparePlay {
    if(self.player.isPreparedToPlay) {
        self.playOrPauseBtn.selected = YES;
        return;
    }
    NSString *isHttpStr = [self.currentMediaURL substringToIndex:4];
    if([isHttpStr isEqualToString:@"http"]) {
        [self.player setShouldAutoplay:NO];
        [self.player prepareToPlay];
            //注册监听预加载视频信息状态
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                         name:MPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                                       object:self.player];
        
        
    }else {
    
        [self.player prepareToPlay];
        self.playOrPauseBtn.selected = YES;
    }
}

/* Notifies observers of a change in the prepared-to-play state of an object
 conforming to the MPMediaPlayback protocol. */
- (void) mediaIsPreparedToPlayDidChange:(NSNotification*)notification
{
    NSLog(@"media is prepared to play did change ");
    if(self.player.isPreparedToPlay) {
        [self.player pause];
    }
    self.playOrPauseBtn.selected = NO;
}

- (BOOL)isPlaying
{
    return self.player.isPlaying;
}

- (void)startPlaying {
        [self.player play];
    [self.playOrPauseBtn setSelected:YES];
    NSString *isHttpStr = [self.currentMediaURL substringToIndex:4];
    if([isHttpStr isEqualToString:@"http"]) {
        //定时器定时更新播放时间
        NSTimeInterval period = 1.0; //设置时间间隔
        NSTimer *timer = [NSTimer timerWithTimeInterval:period target:self selector:@selector(updateProgressInfo) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    }

}

- (void)pausePlaying {
    [self.player pause];
}

- (void)resumePlaying {
    [self.player play];
}

- (void)destroyPlaying {
    @try {
        [self.player stop];
    } @catch (NSException *exception) {
        NSLog(@"停止异常");
    } @finally {
        
    }
    
}

//- (UIView *)currentLiveView {
//    return self.player.view;
//}


#pragma mark - 观察者对应的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
//        AVPlayerItemStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
//        if (AVPlayerItemStatusReadyToPlay == status) {
//            [self removeProgressTimer];
////            [self addProgressTimer];
//        } else {
//            [self removeProgressTimer];
//        }
    }
}

#pragma mark - 重新布局
- (void)layoutSubviews
{
    [super layoutSubviews];
    self.player.view.frame = self.bounds;
}

// 是否显示工具的View
- (IBAction)tapAction:(UITapGestureRecognizer *)sender {
    [self showToolView:!self.isShowToolView];
//    [self removeShowTimer];
//    if (self.isShowToolView) {
//        [self showToolView:YES];
//    }
}

- (IBAction)swipeAction:(UISwipeGestureRecognizer *)sender {
    [self swipeToRight:YES];
}

- (IBAction)swipeRight:(UISwipeGestureRecognizer *)sender {
    [self swipeToRight:NO];
}

- (void)swipeToRight:(BOOL)isRight
{
    // 1.获取当前播放的时间
//    NSTimeInterval currentTime = CMTimeGetSeconds(self.player.currentItem.currentTime);
    NSTimeInterval currentTime = self.player.currentPlaybackTime;
    
    if (isRight) {
        [UIView animateWithDuration:1 animations:^{
            self.forwardImageView.alpha = 1;
        } completion:^(BOOL finished) {
            self.forwardImageView.alpha = 0;
        }];
        currentTime += 10;
        
    } else {
        [UIView animateWithDuration:1 animations:^{
            self.backImageView.alpha = 1;
        } completion:^(BOOL finished) {
            self.backImageView.alpha = 0;
        }];
        currentTime -= 10;
        
    }
    
    if (currentTime >= self.player.duration) {
        
        currentTime = self.player.duration - 1;
    } else if (currentTime <= 0) {
        currentTime = 0;
    }
    self.player.currentPlaybackTime = currentTime;
//
//    [self.player seekToTime:CMTimeMakeWithSeconds(currentTime, NSEC_PER_SEC) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
    
    [self updateProgressInfo];
}




- (void)showToolView:(BOOL)isShow
{
    if (self.progressSlider.tag == 100) {
        
//            [self showToolView:YES];
        [self removeShowTimer];
        self.progressSlider.tag = 20;
        return;
    
    }
    [UIView animateWithDuration:1.0 animations:^{
        self.toolView.alpha = !self.isShowToolView;
        self.isShowToolView = !self.isShowToolView;
    }];
}

// 暂停按钮的监听
- (IBAction)playOrPause:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender == nil) {
        self.playOrPauseBtn.selected = NO;
    }
    if (sender.selected) {
        if(!self.player.isPreparedToPlay) {
            [self.player prepareToPlay];
        }
        [self.player play];
        [self addShowTimer];
        [self addProgressTimer];
    } else {
        [self.player pause];
        [self removeShowTimer];
        [self removeProgressTimer];
    }

}

#pragma mark - 定时器操作
- (void)addProgressTimer
{
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgressInfo) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}

- (void)removeProgressTimer
{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)updateProgressInfo
{
    // 1.更新时间
    self.timeLabel.text = [self timeString];
    
    self.progressSlider.value = (self.player.currentPlaybackTime) / (self.player.duration);
    
    if(self.progressSlider.value == 1)
    {
        self.progressSlider.value = 0;
        self.progressSlider.tag = 100;
//        [self playOrPause:nil];
//        [self sliderValueChange];
        [self.player stop];
        self.finishedPlay = YES;
        self.playOrPauseBtn.selected = NO;
        self.toolView.alpha = 1;
        
        [self removeProgressTimer];
        [self removeShowTimer];
        self.timeLabel.text = @"00:00/00:00";
        return;

    }

}

- (NSString *)timeString
{
    NSTimeInterval duration = (self.player.duration);
    NSTimeInterval currentTime = (self.player.currentPlaybackTime);
    //    if (self.player == nil) {
    //        return @"00:00/00:00";
    //    }
    return [self stringWithCurrentTime:currentTime duration:duration];
}

- (void)addShowTimer
{
    self.showTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateShowTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.showTimer forMode:NSRunLoopCommonModes];
}

- (void)removeShowTimer
{
    [self.showTimer invalidate];
    self.showTimer = nil;
}

- (void)updateShowTime
{
    self.showTime += 1;
    
    if (self.showTime > 2.0) {
        [self tapAction:nil];
        [self removeShowTimer];
        
        self.showTime = 0;
    }
}

#pragma mark - 切换屏幕的方向
- (IBAction)switchOrientation:(UIButton *)sender {
    sender.selected = !sender.selected;
    [self videoplayViewSwitchOrientation:sender.selected];
}



- (void)videoplayViewSwitchOrientation:(BOOL)isFull
{
    if (isFull) {
        //切换到全屏
        BOOL __isPlay = NO;
        if(self.player.isPlaying) {
            __isPlay = YES;
            [self.player pause];
        }
        self.fullVc.delegate = self;
        [self.contrainerViewController.navigationController pushViewController:self.fullVc animated:NO];
        AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
        //允许横屏切换
        appdelegate.allowRotation=YES;
        [self.fullVc setNewOrientation:YES];
        
        self.center = self.fullVc.view.center;

        [self.fullVc.view addSubview:self];
        //全屏时添加返回按钮
        [self.fullVc addBackButton];
        //隐藏状态栏
        [[UIApplication sharedApplication] setStatusBarHidden:TRUE];

        [UIView animateWithDuration:0.15 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
            self.frame = self.fullVc.view.bounds;
            
        } completion:nil];
        
        if(__isPlay) {
         [self resumePlaying];
        }
    } else {
        //还原
        [AppDelegate sharedAppDelegate].allowRotation = YES;
        [self.contrainerViewController.navigationController popViewControllerAnimated:NO];
        [self.fullVc setNewOrientation:NO];
        //隐藏状态栏
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        CGRect tmpFrame = self.frame;
        tmpFrame.size.height = [self.controlDelegate takePlayHeight];

        AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
        appdelegate.allowRotation=NO;
        
        [self.contrainerViewController.view addSubview:self];
        [self.controlDelegate restoreFunc];
        
            [UIView animateWithDuration:0.15 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                self.frame = CGRectMake(0, 0, self.contrainerViewController.view.bounds.size.width,tmpFrame.size.height );
            } completion:nil];
        [self resumePlaying];
    }
}

- (IBAction)slider {
    NSTimeInterval currentTime = self.player.duration * self.progressSlider.value;
    self.player.currentPlaybackTime = currentTime;
    [self.player play];
}

- (IBAction)startSlider {
    [self removeProgressTimer];

}

- (IBAction)sliderValueChange {
    [self removeProgressTimer];
    [self removeShowTimer];
    if (self.progressSlider.value == 1) {
        self.progressSlider.value = 0;
    }
    NSTimeInterval currentTime = self.player.duration * self.progressSlider.value;
    self.player.currentPlaybackTime = currentTime;
    self.timeLabel.text = [self stringWithCurrentTime:currentTime duration:self.player.duration];
    [self addShowTimer];
    [self addProgressTimer];
    
}

- (NSString *)stringWithCurrentTime:(NSTimeInterval)currentTime duration:(NSTimeInterval)duration
{
    NSInteger dMin = duration / 60;
    NSInteger dSec = (NSInteger)duration % 60;
    
    NSInteger cMin = currentTime / 60;
    NSInteger cSec = (NSInteger)currentTime % 60;
    
    NSString *durationString = [NSString stringWithFormat:@"%02ld:%02ld", dMin, dSec];
    NSString *currentString = [NSString stringWithFormat:@"%02ld:%02ld", cMin, cSec];
    
    return [NSString stringWithFormat:@"%@/%@", currentString, durationString];
}

#pragma mark - 懒加载代码
- (FullViewController *)fullVc
{
    if (_fullVc == nil) {
        _fullVc = [[FullViewController alloc] init];
    }
    return _fullVc;
}


-(void)restoreView
{
    //还原控件---在界面被POP前，先将视频控件添加到原聊天界面
    self.fullBtn.selected = NO;
    [self.controlDelegate restorePlay];
}



@end
